package cn.jeefast.modules.upload.controller;

import cn.jeefast.common.exception.RRException;
import cn.jeefast.common.utils.R;
import cn.jeefast.modules.upload.service.FileUploadService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * FileUploadController
 *
 * @author WY
 * @date 2018-08-29 0029
 */
@RestController
@RequestMapping("/api")
@CrossOrigin
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 富文本上传
     */
    @RequestMapping("/frUpload")
    public R frUpload(MultipartFile file, String folder) {
        try {
            return R.ok("").put("link", "http://localhost:8903" + fileUploadService.oneUpload(file, folder));
        } catch (Exception e) {
            throw new RRException("上传失败!", e);
        }
    }

    /**
     * 上传
     */
    @RequestMapping("/upload")
    public R upload(MultipartFile file, String folder) {
        try {
            return R.ok("").put("path", fileUploadService.oneUpload(file, folder));
        } catch (Exception e) {
            throw new RRException("上传失败222!", e);
        }
    }

    /**
     * 上传模板并得到大小
     */
    @RequestMapping("/upload3")
    public R upload3(MultipartFile file, String folder) {
        try {
            return fileUploadService.oneUpload3(file, folder);
        } catch (Exception e) {
            throw new RRException("上传失败222!", e);
        }
    }


    /**
     * @param
     * @return
     * @Title: 上传图片，并保存缩略图
     * @author: lzl
     * @Description:
     */
    @RequestMapping("/upload2")
    public R upload2(MultipartFile file, String folder) {
        try {
            return fileUploadService.oneUpload2(file, folder);
        } catch (Exception e) {
            throw new RRException("上传失败!", e);
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delFile")
    public R delFile(String filePath, String folder) {
        try {
            List<String> delPicList = new ArrayList<>();
            String[] picList = StringUtils.split(filePath, ",");
            Arrays.asList(picList).forEach(e -> {
                delPicList.add(e);
            });
            fileUploadService.delete(delPicList, folder);
            return R.ok("");
        } catch (Exception e) {
            throw new RRException("上传失败!", e);
        }
    }
}
